<script setup lang="ts">
  import {
    Card,
    Button,
    Popover,
    Input,
    Divider,
    List,
    ListItem,
    Message,
  } from '@arco-design/web-vue';
  import { IconRefresh } from '@arco-design/web-vue/es/icon';
  import { ref, computed, watch, shallowRef } from 'vue';
  import CommunityList from './CommunityList.vue';
  import imgIcon from '/@/assets/pins/c_img.svg';
  import topicIcon from '/@/assets/pins/c_topic.svg';
  import { publishPin } from '/@/api/web/pin';
  import { Upload } from '/@/components/Upload';
  import { stringifyArrayValue } from '/@/utils/helper';
  import type { FileItem } from '/@/components/Upload';
  import { SimpleEditor } from '/@/components/SimpleEditor';
  import type { ISimpleEditor } from '/@/components/SimpleEditor';
  import EmojiPicker from '/@/components/EmojiPicker.vue';

  // const emits = defineEmits(['input']);

  const editorRef = shallowRef<ISimpleEditor>();
  const fileList = ref<FileItem[]>([]);
  const maxCount = 1000;
  const contentValue = ref('');
  const communityInfo = ref<any>();
  // const communityRef = ref();

  const showPlaceholder = computed(() => {
    return contentValue.value?.length === 0;
  });
  const currentCount = computed(() => {
    return contentValue.value?.length;
  });

  // 选择表情包
  const selectEmoji = (val: string) => {
    editorRef.value?.insertHtml(val);
  };
  interface topicRecord {
    id: number;
    topic: string;
  }
  const topicList: topicRecord[] = [
    {
      id: 1,
      topic: 'web3有什么价值',
    },
    {
      id: 2,
      topic: 'DAO的自力更生之道',
    },
    {
      id: 3,
      topic: '零工经济的新模式',
    },
    {
      id: 4,
      topic: 'NFT记录人生足迹',
    },
    {
      id: 5,
      topic: '用DAO实现自我成长',
    },
  ];
  function handleSeleteTopic(val: topicRecord) {
    const element = editorRef.value?.getEditableContainer();
    if (element) {
      const n = element.querySelector('span[data-node="theme"]');
      if (n) {
        n.id = `${val.id}`;
        n.textContent = `#${val.topic}#`;
      } else {
        const topicSpan = `<span data-node='theme' id='${val?.id}' contenteditable='false' style='color: #1E80FF;'>#${val?.topic}#</span>&nbsp;&nbsp;`;
        // if (editorRef.value) {
        //   editorRef.value.innerHTML = topicSpan;
        // }
        editorRef.value?.prependHtml(topicSpan);
      }
    }
  }
  function handleSkip() {
    show.value = false;
  }
  function handleChange(item: any) {
    show.value = false;
    communityInfo.value = item;
  }

  const show = ref<boolean>(false);

  // 上传组件
  const uploadRef = ref();

  // 是否在发布中
  const isPublishingRef = ref(false);

  // 是否图片全部上传完成
  const getIsAllDone = computed(() => {
    return (
      fileList.value.length < 1 ||
      fileList.value.every((item) => {
        return item.status === 'done' || item.status === 'error';
      })
    );
  });

  // 发布沸点
  const publishHotspot = async () => {
    try {
      // 获取上传之后的图片列表
      const img = fileList.value
        .map((item) => {
          return item.url || '';
        })
        .filter(Boolean);

      const result = await publishPin({
        content: contentValue.value,
        img: stringifyArrayValue(img),
        community_id: communityInfo.value?.id,
      });
      Message.success('发布成功');

      // 清空沸点内容
      if (editorRef.value) {
        editorRef.value.clear();
        fileList.value = [];
      }
      return result;
    } catch (error) {
      Message.error((error as Error).message || '发布失败');
    } finally {
      isPublishingRef.value = false;
    }
  };

  // 状态切换为发布中
  const onpublishPin = async () => {
    isPublishingRef.value = true;
    uploadRef.value?.submit();
  };

  const onCreated = (editor: ISimpleEditor) => {
    editorRef.value = editor;
  };

  // 等待图片上传完成
  watch([isPublishingRef, getIsAllDone], async () => {
    if (isPublishingRef.value && getIsAllDone.value) {
      publishHotspot();
    }
  });

  // 打开文件选择
  const triggerInputClick = () => {
    uploadRef.value?.triggerInputClick();
  };
</script>
<template>
  <div class="c-pin-editor">
    <card hoverable :bordered="false" class="mb-[10px] rounded-[8px] bg-[rgba(255,255,255,0.8)]">
      <div
        class="editor-box mb-[12px] rounded-[8px]"
        :class="showPlaceholder ? 'showPlaceholder' : ''"
        placeholder="快来和星友分享新鲜事123"
      >
        <SimpleEditor
          v-model="contentValue"
          class="min-h-[80px] max-h-[148px]"
          @on-created="onCreated"
        />

        <div class="topic-wrapper px-2 pb-2 box-border flex items-center justify-between">
          <popover
            v-model:popup-visible="show"
            trigger="click"
            position="bl"
            class="community-content"
          >
            <Button type="outline" shape="round" class="!border-none !bg-white">
              <template #icon>
                <IconRefresh />
              </template>
              {{ communityInfo ? communityInfo.name : '请选择圈子' }}</Button
            >
            <template #content>
              <CommunityList class="w-[360px]" @skip="handleSkip" @change="handleChange" />
            </template>
          </popover>
          <span class="text-gray-400"> {{ currentCount }}/{{ maxCount }}</span>
        </div>
        <div v-show="fileList.length > 0" class="upload-pics">
          <Upload ref="uploadRef" v-model:file-list="fileList" :limit="9" :autoUpload="false" />
        </div>
      </div>
      <div class="editor-tools flex items-center justify-between select-none">
        <div class="tools-left flex items-start cursor-pointer">
          <EmojiPicker @select="selectEmoji" />

          <span class="tools-left-item flex items-center mx-4 text-[rgba(0,0,0,0.5)]">
            <img :src="imgIcon" class="w-[23px] h-[18px] mr-[8px]" />
            <label for="imageUpload" @click="triggerInputClick"> 图片</label>
          </span>
          <popover title="话题" trigger="click" position="bl" content-class="emoji-content">
            <span class="tools-left-item flex items-center mx-4 text-[rgba(0,0,0,0.5)]">
              <img :src="topicIcon" class="w-[22px] h-[18px] mr-[8px]" />
              话题
            </span>
            <template #content>
              <div style="height: 300px; width: 240px">
                <Input placeholder="搜索话题名称" allow-clear />
                <Divider />
                <div style="height: 196px; overflow: auto">
                  <List :bordered="false" :split="false">
                    <list-item
                      v-for="item of topicList"
                      :key="item.id"
                      @click="handleSeleteTopic(item)"
                      >{{ item?.topic }}</list-item
                    >
                  </List>
                </div>
              </div>
            </template>
          </popover>
        </div>
        <div class="tools-right">
          <Button
            type="primary"
            class="!px-10"
            :disabled="contentValue.length === 0"
            :loading="isPublishingRef"
            @click="onpublishPin"
          >
            {{ isPublishingRef ? '发布中...' : '发布' }}</Button
          >
        </div>
      </div>
    </card>
  </div>
</template>

<style scoped>
  .community-content :deep(.arco-popover-popup-content) {
    padding: 12px 0px !important;
  }

  .editor-box {
    position: relative;
    width: 100%;
    height: auto;
    font-size: 14px;
    line-height: 22px;
    background-color: #f8f8f8;
  }

  .editor-content {
    outline-style: none;
    line-height: 22px;
    padding: 6px 10px;
    box-sizing: border-box;
    overflow: auto;
  }

  .showPlaceholder::before {
    content: attr(placeholder);
    position: absolute;
    top: 6px;
    left: 10px;
    color: #bbb;
    pointer-events: none;
  }

  .tools-left .tools-left-item:hover {
    color: #1e80ff !important;
  }
</style>
